<template>
  <div class="setting-content inside-comment">
    <el-scrollbar height="calc(100vh - 170px)">
      <h2 class="setting-header">
        <strong>部门管理</strong>
      </h2>
      <div class="top-info">
        <!-- <div class="right-box">
          <SearchCmp
            v-if="searchCmpArray.length"
            :searchCmpArray="searchCmpArray"
            :searchForm="queryData"
            @onSubmit="getTableData"
          />
        </div> -->
        <el-button type="primary" @click="addNode()">添加部门</el-button>
      </div>
      <RuifoxTable
        v-loading="tableLoading"
        v-model:tableData="tableData"
        :field-list="fieldList"
        :lazy="true"
        v-model:defaultExpandTree="expandedKeys"
        row-key="id"
      >
        <template #options="{ element }">
          <div class="table-td-option unmover">
            <el-button
              type="primary"
              link
              @click="addNode(element)"
            >
              添加
            </el-button>
            <el-button
              type="primary"
              link
              @click="editNode(element)"
            >
              编辑
            </el-button>
            <el-button
              type="primary"
              link
              @click="removeNode(element)"
            >
              删除
            </el-button>
          </div>
        </template>
       
      </RuifoxTable>

      <!-- 添加部门 对话框 -->
      <el-drawer v-model="addNodeVisible" direction="ltr" size="800px" :title="addNodeFlag?'增加部门':'编辑部门'" width="500px" class="addClass-dialog">
        <el-form ref="formRef" :rules="rules" :model="addNodeForm" label-width="100px">
          <el-form-item label="上级部门" prop="pid" v-if="isRoot">
            <el-cascader :options="tableData" :props="props1" v-model="addNodeForm.pid" :show-all-levels="false" popper-class="pid-cascader" placeholder="选择上级">
              <template #default="{ data }">
                <p @click="handleChooseParent(data)">{{data.name}}</p>
              </template>
            </el-cascader>
          </el-form-item>
          <el-form-item label="部门名称" prop="name">
            <el-input placeholder="输入名称" v-model="addNodeForm.name"></el-input>
          </el-form-item>
          <el-form-item label="部门编码">
            <el-input placeholder="输入部门编码" v-model="addNodeForm.code"></el-input>
          </el-form-item>
          <el-form-item label="部门描述">
            <el-input placeholder="输入部门描述" v-model="addNodeForm.description"></el-input>
          </el-form-item>
          <el-form-item label="自定义说明">
            <TinymceEditor
              v-model:modelValue="addNodeForm.addition"
              :minHeight="500"
            />
          </el-form-item>
          <el-form-item label="部门负责人">
            <el-select v-model="addNodeForm.leaderId" placeholder="请选择部门负责人" style="width: 240px">
              <el-option
                v-for="item in leaderList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="开放注册" prop="openingRegister">
            <el-switch v-model="addNodeForm.openingRegister"></el-switch>
          </el-form-item>
          <el-form-item label="申请审核配置ID" prop="enrollmentConfigId" v-if="addNodeForm.openingRegister">
            <el-input placeholder="申请审核配置ID" v-model="addNodeForm.enrollmentConfigId"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="addNodeVisible = false">取消</el-button>
            <el-button type="primary" @click="appendNode(formRef)">确认</el-button>
          </span>
        </template>
      </el-drawer>
    </el-scrollbar>
  </div> 
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessageBox } from "element-plus";
import {
  getDepartTree,
  saveDepart,
  // changeDepart,
  deleteDepart,
  getDepartById
} from "@/api/depart";
import { getUserList } from "@/api/user";
import { ElMessage } from "element-plus";
import { useStore } from "vuex";

const store = useStore();

// const searchCmpArray = ref([
//   { label: "部门名称", key: "name" },
// ]);


//树形控件相关操作
const addNodeVisible = ref(false)
const addNodeFlag = ref(true)
const defaultNodeFormData = {
  id: "", 
  pid: "",
  name: "",
  code: "",
  description: "",
  addition: "",
  leaderId: "",
  openingRegister: false,  //	是否开放注册
  enrollmentConfigId: 0,   //申请审核配置ID
  sortOrder: "",  //排序顺序
  sortWeight: "",  //排序权重
};
const addNodeForm = ref({ ...defaultNodeFormData });

//级联选择器
const props1 = {
  checkStrictly: true,
  value: "id",
  label: "name",
  children: "children",
  expandTrigger: 'hover',
}

const handleChooseParent = (data) => {
  console.log(data);
  addNodeForm.value.pid = data.id
  // parentCategory.value = structuredClone(data)
}

//添加节点 没有传参就是新增根节点
const isRoot = ref(true)
const addNode = (row) => {
  addNodeFlag.value = true
  addNodeForm.value = { ...defaultNodeFormData };
  if(row && row.id){
    addNodeForm.value.pid = row.id
    isRoot.value = true
  } else {
    //根节点 没有上级部门
    addNodeForm.value.pid = ""
    isRoot.value = false
  }
  addNodeVisible.value = true
}
//编辑节点
const editNode = async (row) => {
  if(row.pid){
    isRoot.value = true
  } else {
    isRoot.value = false
  }
  //根据部门id获取部门详细信息
  const res = await getDepartById({departId:row.id})
  if (res.code === 20000) {
    addNodeForm.value = res.data;
    addNodeForm.value.addition = JSON.parse(addNodeForm.value.addition);
    addNodeFlag.value = false;
    addNodeVisible.value = true;
    console.log("addNodeForm.value",addNodeForm.value);
  }
}
const formRef = ref()
const rules = reactive({
  name: [{ required: true, message: '请输入部门名称', trigger: 'blur' }],
})
//提交公告
const appendNode = async (formEl) => {
  if (!formEl){
    ElMessage.warning("请填写完整公告内容");
    return
  } 
  await formEl.validate(async (valid) => {
    if (valid) {
      addNodeForm.value.addition = JSON.stringify(addNodeForm.value.addition);
      let res;
      res = await saveDepart(addNodeForm.value);
      if (res.code == 20000) {
        ElMessage.success('保存成功');
        addNodeVisible.value = false;
        getAllData()
      } else {
        console.log(res.message);
      }
    }
  })
}

//删除节点
const removeNode = (row) => {
  ElMessageBox.confirm("确定删除该部门？", "删除确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const res = await deleteDepart({departId:row.id})
    if (res.code == 20000) {
      ElMessage.success('删除成功');
      getAllData()
    } else {
      console.log(res.message);
    }
  })
}


//获取组织结构数据
const expandedKeys = ref([]); //表格 展开层id
const tableData = ref()
const getAllData = async () => {
  const res = await getDepartTree({departId: "root"})
  if (res.code == 20000) {
    tableData.value = res.data.children;
    console.log("tableData.value",tableData.value);
    //递归显示第一层子节点
    tableData.value.forEach(element => {
      expandedKeys.value.push(element.id)
    });
  }
}

//获取负责人 走主系统根据用户角色查询
const leaderList = ref([])
const getUser = async () => {
  console.log(store);
  
  const res = await getUserList({
    pageSize: 15,
    currentPage: 1,
    groupId: store.state.base.userInfo.groupId
  })
  console.log("获取管理员res",res);
  if (res.code == 20000) {
    leaderList.value = res.data.list
  }
}

//表格展示字段
const fieldList = ref([
  {
    title: "名称",
    name: "name",
  },
  {
    title: "部门编码",
    name: "code",
  },
  {
    title: "说明",
    name: "description",
  },
  {
    title: "部门负责人",
    name: "leaderName",
  },
  // {
  //   title: "允许加入",
  //   name: "allowJoining",
  // },
  // {
  //   title: "是否审核",
  //   name: "needCheck",
  // },
  { 
    title: "操作",
    name: "options",
    width: 200,
  },
]);
onMounted(async() => {
  await getAllData()
  await getUser()
})
</script>

<style scoped lang="scss">
.top-info{
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  .right-box{
    display: flex;
    button{
      margin-left: 10px;
    }
  }
}

</style>